<template>
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 角色列表卡片 -->
        <el-card>
            <!-- 添加角色工具栏 -->
            <el-row>
              <el-col >
                  <el-button type="primary">添加角色</el-button>
              </el-col>
            </el-row>
            <!-- 角色列表 -->
            <el-table :data="rolesList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- 采用栅格布局渲染角色下的权限 -->
                        <el-row :class = "['bdbottom', 'vcenter', index1 === 0 ? 'bdtop' : '']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)" type="">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级三级权限 -->
                            <el-col :span="19">
                                <!-- 循环渲染二级权限 -->
                                <el-row :class="[index2 == 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, index2) in item1.children" :key="item2.id">
                                    <!-- 二级权限 -->
                                    <el-col :span="6">
                                        <el-tag closable @close="removeRightById(scope.row, item2.id)" type="success">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <!-- 三级标签 -->
                                        <el-tag closable @close="removeRightById(scope.row, item3.id)" type="warning" v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 展示分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="30%" @close="setRightDialogClose()">
            <!-- 树形控件 -->
            <el-tree ref="treeRef" :data="rightslist" :props="treeProps" node-key="id" :default-checked-keys="defKeys" show-checkbox default-expand-all></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        return {
            // 所有角色列表
            rolesList: [],
            // 展示权限对话框
            setRightDialogVisible: false,
            // 所有权限列表
            rightslist: [],
            // 树形控件属性绑定对象
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            // 默认选中树形节点key的数组
            defKeys: [],
            // 分配权限时的角色ID
            roleId: ''
        }
    },
    created () {
        // 加载页面时获取角色列表
        this.getRolesList()
    },
    methods: {
        // 获取角色列表
        async getRolesList () {
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$msg.error('获取角色列表失败')
            this.rolesList = res.data
        },
        // 根据ID删除权限
        removeRightById (role, rightId) {
            this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 删除该角色下的权限
                const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if (res.meta.status !== 200) return this.$msg.error('删除角色下权限失败')
                // 为角色重新赋值权限数据，防止页面整体刷新。
                role.children = res.data
                this.$msg({
                    type: 'success',
                    message: '删除成功!'
                })
            }).catch(() => {
                this.$msg({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        // 展示配置权限对话框
        async showSetRightDialog (role) {
            this.roleId = role.id
            // 获取权限列表树形数据
            const { data: res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) return this.$msg.error('获取权限列表失败')
            this.rightslist = res.data
            // 递归获取三级权限节点
            this.getLeafKeys(role, this.defKeys)
            // 显示对话框
            this.setRightDialogVisible = true
        },
        // 通过递归形式，获取节点下所有上级权限的ID，保存到defKeys
        getLeafKeys (node, arr) {
            // 如果是三级权限节点，将ID保存到数组中
            if (!node.children) {
                return arr.push(node.id)
            }
            // 递归
            node.children.forEach(item => {
                this.getLeafKeys(item, arr)
            })
        },
        // 监听对话框关闭
        setRightDialogClose () {
            this.defKeys = []
        },
        // 授权角色权限点击事件
        async allotRights () {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idsStr = keys.join(',')
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idsStr })
            if (res.meta.status !== 200) return this.$msg.error('角色授权失败')
            this.$msg.success('授权成功')
            this.getRolesList()
            this.setRightDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 8px;
}

.bdtop {
    border-top: 1px solid #EEE;
}

.bdbottom {
    border-bottom: 1px solid #EEE;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>
